package mwa.cs.rc.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.ArDAO;
import mwa.cs.dao.RcTransDDAO;
import mwa.cs.dao.RcTransMDAO;
import mwa.cs.dao.RequestDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Ar;
import mwa.cs.model.RcTransM;
import mwa.cs.model.Request;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS53000Srvl
 */
public class CS53000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private String vaUrlAddress;
	private String vaAgentBrowser;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS53000Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    @SuppressWarnings({ "unchecked", "unused" })
	public void processRequest(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
    	
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
    	request.setCharacterEncoding("UTF-8");
   		response.setCharacterEncoding("UTF-8");
   		response.setContentType("text/JSON");
   		String vaProcessType = request.getParameter("methodType");
		if (vaProcessType.equals("getDataRC")){
			getDataRcTransM(request, response);
		} else {
			saveData(request, response);
		}
	}

    @SuppressWarnings("unchecked")
	public void saveData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		Database db = new Database();
		RcTransM voRCTransM = new RcTransM();
		RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);
		RcTransDDAO voRcTransDDAO = new RcTransDDAO(db);
		RequestDAO voRequestDAO = new RequestDAO(db);
		ArDAO voArDAO = new ArDAO(db);
		Request voRequest = new Request();
		Ar voAr = new Ar();
		int vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		String vaSerialNumber = request.getParameter("serialNumber").trim();
		String vaStatus = "C";
		String vaRcReason = request.getParameter("rcReason").trim();
		String vaCancelDate = JDate.getDate();
		String vaCancelTime = JDate.getTime();
		String vaCancelEmployee = request.getSession().getAttribute("user_id").toString();
		String vaUpdateDate = JDate.getDate();
		String vaUpdateTime = JDate.getTime();
		
		Map<String, Object> voMapRcTransD = new HashMap<String, Object>();
		voMapRcTransD = voRcTransDDAO.searchRcTransDForResetData(Long.parseLong(vaSerialNumber));
		String billNumber = "";
		// set ค่า RcTransM
		voRCTransM.setVaStatus(vaStatus);
		voRCTransM.setVaCancelReason(vaRcReason);
		voRCTransM.setVaCancelDate(vaCancelDate);
		voRCTransM.setVaCancelTime(vaCancelTime);
		voRCTransM.setVaCancelEmployee(vaCancelEmployee);
		voRCTransM.setVnUpdateUserId(vnUserId);
		voRCTransM.setVaUpdateDate(vaUpdateDate);
		voRCTransM.setVaUpdateTime(vaUpdateTime);
		voRCTransM.setVnSiteId(vnSiteId);
		voRCTransM.setVnSerialNumber(Long.parseLong(vaSerialNumber));
		try {
			db.beginTransaction();
			boolean result = voRcTransMDAO.cancelRcTransM(voRCTransM, vaSerialNumber);
				if (result) {
				if (voMapRcTransD == null) { // check reset AR
					// set ค่า AR
					voAr.setVaReceiveDate("");
					voAr.setVaReceiveTime("");
					voAr.setVnReceiveEmployee(0);
					voAr.setVnUpdateUserId(vnUserId);
					voAr.setVaUpdateDate(vaUpdateDate);
					voAr.setVaUpdateTime(vaUpdateTime);
					voAr.setVnSiteId(vnSiteId);
//					voAr.setVnSerialNumber(Integer.parseInt(vaSerialNumber));
					result = voArDAO.resetArForCancelReceive(voAr,vaSerialNumber);
					if (result) {
						voObject.put("message", "success");
						db.commit();
					} else {
						voObject.put("message", "fail");
					}
				} else { // reset Request
					billNumber = "" + voMapRcTransD.get("BILL_NUMBER");
					// set ค่า Request
					voRequest.setVaStatus("1");
					voRequest.setVnUpdateUserId(vnUserId);
					voRequest.setVaUpdateDate(vaUpdateDate);
					voRequest.setVaUpdateTime(vaUpdateTime);
					voRequest.setVnSiteId(vnSiteId);
					voRequest.setVaRequestNumber(billNumber);
					result = voRequestDAO.resetRequestForCancelReceive(voRequest);
					if (result) {
						voObject.put("message", "success");
						db.commit();
					} else {
						voObject.put("message", "fail");
					}
				}
			} else {
				voObject.put("message", "fail");
			}
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS53000", JDate.getDate(), JDate.getTime(),vnUserId, "CS53000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			voObject.put("message", "fail");
		}
		db.close();
		voOut.print(voObject.toJSONString());
    }
    
    @SuppressWarnings("unchecked")
	public void getDataRcTransM(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		Database db = new Database();
    	RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);
    	RcTransDDAO voRcTransDDAO = new RcTransDDAO(db);
		String vaPutSerialNumber = request.getParameter("serialNumber").trim();
		String vaSerialNumber = "";
		String vaAccount = "";
		String vaPayerName = "";
		String vaPayerAddress = "";
		String vaPenalty = "";
		String vaStatus = "";
		String vaCloseDate = "";
		JSONArray voSequence = new JSONArray();
		JSONArray voDescription = new JSONArray();
		JSONArray voTotalAmount = new JSONArray();
		JSONArray vaVatAmount = new JSONArray();
		JSONArray voBillAmount = new JSONArray();
		
		Map<String, Object> voMapRcTransM = new HashMap<String, Object>();
		List<Map<String, Object>> voArrayList = null;
		Map<String, Object> voMapRcTransD = new HashMap<String, Object>();
		voMapRcTransM = voRcTransMDAO.searchRcTransMForCancel(vnSiteId, Long.parseLong(vaPutSerialNumber));
		if (voMapRcTransM == null) {
			voObject.put("message", "resultNull");
		} else {
			vaStatus = ""+ voMapRcTransM.get("STATUS");
			vaCloseDate = ""+ voMapRcTransM.get("CLOSE_DATE");
			if (!vaCloseDate.equals("null")) {
				voObject.put("message", "closeDate");
			} else if (vaStatus.equals("0")) {
				voObject.put("message", "status");
			} else {
				vaSerialNumber = ""+ voMapRcTransM.get("SERIAL_NUMBER");
				vaAccount = ""+ voMapRcTransM.get("ACCOUNT");
				vaPayerName = ""+ voMapRcTransM.get("PAYER_NAME");
				vaPayerAddress = ""+ voMapRcTransM.get("PAYER_ADDRESS");
				vaPenalty = ""+ voMapRcTransM.get("PENALTY");
				voArrayList = voRcTransDDAO.searchRcTransDForCancel(Long.parseLong(vaSerialNumber));
				if (voArrayList.size() == 0) {
					voObject.put("message", "resultNull");
				} else {
					for (int i = 0; i < voArrayList.size(); i++) {
						voMapRcTransD = voArrayList.get(i);	
						voSequence.add(voMapRcTransD.get("SEQ"));
						voDescription.add(voMapRcTransD.get("DESCRIPTION"));
						voTotalAmount.add(voMapRcTransD.get("TOTAL_AMOUNT"));
						vaVatAmount.add(voMapRcTransD.get("VAT_AMOUNT"));
						voBillAmount.add(voMapRcTransD.get("BILL_AMOUNT"));
					}
					voObject.put("serialNumber", vaSerialNumber);
					voObject.put("account", vaAccount);
					voObject.put("payerName", vaPayerName);
					voObject.put("payerAddress", vaPayerAddress);
					voObject.put("penalty", vaPenalty);
					voObject.put("sequence", voSequence);
					voObject.put("description", voDescription);
					voObject.put("totalAmount", voTotalAmount);
					voObject.put("vatAmount", vaVatAmount);
					voObject.put("billAmount", voBillAmount);
				}
			}
		}
		db.close();
    	voOut.print(voObject.toJSONString());
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
